<template>
  <div class="public_height100 p20 pub_bgColorFFF">
    <div class="table_content">
      <!-- ====== 表格上方的筛选条件 start ======-->
      <div class="table_filter flex_space_between">
        <div class="flex_start ">
          <div class="table_filter_search">
            <el-radio-group v-model="params.commonTag" size="small" @input="getDataList">
              <el-radio-button v-for="item in applyOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div class="flex_end">
          <div v-if="params.commonTag == 2">
            <el-button type="text" class="w108 pub_button pub_buttonGreen" @click="showDilogBtn('addDialogVisible')">
              <img src="@/assets/img/orderManagement/add.png" alt="添加单位" />
              <span class="ml5">添加单位</span>
            </el-button>
          </div>
          <div v-if="params.commonTag == 2 || roleType == 1" class="ml12">
            <el-button type="text" class="w108 pub_button pub_buttonRed" @click="delteDataBtn">
              <img src="@/assets/img/orderManagement/delete.png" alt="批量删除" />
              <span class="ml5">批量删除</span>
            </el-button>
          </div>
          <div v-if="roleType === 1 && params.commonTag == 4" class="ml12">
            <el-button type="text" class="w108 pub_button pub_buttonGreen" @click="batchAuitBtn">
              <span class="ml0">批量审核</span>
            </el-button>
          </div>
          <div v-if="roleType == 1" class="ml12">
            <el-button type="text" class="w108 pub_button" @click="downloadFile">
              <img src="@/assets/img/orderManagement/download.png" alt="下载模板" />
              <span class="ml5">下载模板</span>
            </el-button>
          </div>
          <div v-if="roleType == 1" class="ml12">
            <el-upload ref="upload" class="avatar-uploader" :show-file-list="false" action="#" :on-change="uploadChange" :auto-upload="false">
              <el-button type="text" class="w80 pub_button">
                <img src="@/assets/img/orderManagement/import.png" alt="导入" />
                <span class="ml5">导入</span>
              </el-button>
            </el-upload>
          </div>
        </div>
      </div>
      <!-- ====== 表格上方的筛选条件 end ======-->
      <el-table ref="multipleTable" size="mini" :data="tableData" tooltip-effect="dark" border :height="`${536 * $f}px`" class="wp100 mt12" @selection-change="handleSelectionChange">
        <el-table-column v-if="params.commonTag != 1 || roleType == 1" key="selection" type="selection" align="center" :width="`${55 * $f}`" />
        <el-table-column key="unit" label="单位名称" show-overflow-tooltip prop="unit" align="center" />
        <el-table-column v-if="params.commonTag != 1 || roleType == 1" key="operation" label="操作" align="center" :width="`${120 * $f}`">
          <template slot-scope="{ row }">
            <el-button v-if="params.commonTag == 2" type="text" class="pub_button public_1EB398_btn" size="mini" @click="editBtnClick(row)">编辑</el-button>
            <el-button v-if="params.commonTag == 2 || roleType == 1" type="text" class="pub_button public_F16363_btn" size="mini" @click="delBtnClick(row)">删除</el-button>
            <el-button v-if="params.commonTag == 4" type="text" class="pub_button public_1EB398_btn" size="mini" @click="auditBtnClick(row)">审核</el-button>
          </template>
        </el-table-column>
        <template slot="empty">
          <PageEmptyData />
        </template>
      </el-table>
      <div ref="pubPageinationRef" class="pub_pageination flex_center mt18">
        <el-pagination background :page-size="params.pageSize" :current-page.sync="params.pageNum" layout="total,prev, pager, next,sizes" :total="params.total" @current-change="changePage" @size-change="changeSize"> </el-pagination>
      </div>
    </div>
    <!-- 审核提示 -->
    <auditDialog :multiple-selection="multipleSelection" :visible="auditDialogVisible" @close="closeDialog" @submit="confirmAudit" />
    <!-- 删除提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deleteDialogVisible" @close="closeDialog" @submit="confirmDelete" />
    <!-- 添加单位 -->
    <PageDialog :show-apply="showApply" :title="addParams.id ? '编辑计量单位' : '添加计量单位'" :dialog-visible="addDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmAdd" @apply="applyBtnClick">
      <el-form ref="ruleForm" :model="addParams" label-width="4.5rem" class="pub_form_item">
        <el-form-item label="计量单位">
          <el-input v-model="addParams.unit" placeholder="请输入计量单位" class="pub_input" :maxlength="30" />
        </el-form-item>
      </el-form>
    </PageDialog>
  </div>
</template>
<script>
import tableFun from '@/mixin/tableFun.js';
export default {
  mixins: [tableFun],
  data() {
    return {
      params: { commonSearch: '', commonTag: 1, total: 0, pageSize: 20, pageNum: 1 },
      addParams: { id: '', unit: '' },
      showApply: false
    };
  },
  created() {
    this.initParams();
  },
  methods: {
    //初始化参数
    initParams() {
      const { messageContent, sendUserId } = this.$route.query;
      if (sendUserId && messageContent && this.roleType === 1) {
        this.params.commonSearch = messageContent;
        this.params.commonTag = 4;
      }
      this.getDataList();
    },
    downloadFile() {
      const link = document.createElement('a');
      link.href = '/static/files/计量单位导入模板.xlsx'; // 直接放在 public 根目录下
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 上传文件
    async uploadChange(file) {
      const form = new FormData();
      form.append('file', file.raw);
      let res = await this.$api.postFile(this.$url.uploadMeasurementInfo, form);
      if (res) {
        this.$message({ message: '上传成功', type: 'success' });
        this.params.commonTag = this.roleType == 1 ? 1 : 2;
        this.getDataList();
      } else {
        this.$message.error('上传失败');
      }
    },
    //关闭弹窗
    closeDialog() {
      this.auditDialogVisible = false;
      this.selectedRow = null;
      this.multipleSelection = [];
      this.deleteDialogVisible = false;
      this.addDialogVisible = false;
      this.addParams = Object.assign({}, this.$options.data().addParams); //重置参数
    },
    async getDataList() {
      this.tableData = [];
      let res = await this.$api.get(this.$url.unitPageList, this.params);
      this.tableData = res.rows;
      this.params.total = res.total;
    },
    //确认删除
    async confirmDelete() {
      let res = null;
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        let idArr = this.multipleSelection.map(val => val.id);
        res = await this.$api.post(this.$url.unitDeleteBatch, idArr);
      } else {
        res = await this.$api.post(this.$url.unitDelete, { id: this.selectedRow.id });
      }
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('删除成功');
        this.handleSearch();
      } else {
        this.$message.success('删除失败');
      }
    },
    //确认添加
    async confirmAdd() {
      let { unit, id } = this.addParams;
      if (!unit) {
        return this.$message.warning('请输入计量单位');
      }
      let url = id ? this.$url.unitUpdate : this.$url.unitAdd;
      let res = await this.$api.post(url, this.addParams);
      if (res.code === 200) {
        this.closeDialog();
        this.handleSearch();
        this.$message.success(id ? '更新成功' : '新增成功');
      } else {
        this.showApply = true;
        this.$message.error(res.msg);
      }
    },
    //确认审核
    async confirmAudit() {
      let idArr = [];
      let applyContent = null;
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        idArr = this.multipleSelection.map(val => val.id);
        applyContent = this.multipleSelection.map(val => val.unit).join(',');
      } else {
        idArr.push(this.selectedRow.id);
        applyContent = this.selectedRow.unit;
      }
      let res = await this.$api.post(this.$url.unitAudit, idArr);
      const { messageContent, sendUserId, messageId } = this.$route.query;
      if (sendUserId && applyContent == messageContent) {
        await this.$api.post(this.$url.message, { messageTitle: '计量单位审批', messageContent: messageContent + '计量单位审核已通过，已纳入公共数据，您可在公共数据中继续添加相关信息', receiveUserId: sendUserId });
        await this.$api.get(this.$url.messageDetail, { id: messageId });
      }
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('审核通过');
        this.handleSearch();
      } else {
        this.$message.success('审核失败');
      }
    },
    //加速审批
    async applyBtnClick() {
      await this.$api.post(this.$url.message, { messageTitle: '计量单位审批', messageContent: this.addParams.unit, receiveUserId: 1 });
      await this.$api.post(this.$url.sendEmail, { subject: '计量单位审批', text: this.addParams.unit });
      this.$message.success('已加急，审批后会走站内信通知');
      this.showApply = false;
      this.closeDialog();
    }
  }
};
</script>
<style lang="less" scoped>
.table_content {
  height: calc(100% - 49px);
}
.addOrder {
  .el-form-item {
    margin-bottom: 0px;
  }
}
</style>
